#pragma once
#ifndef H_DXSETUP
#define H_DXSETUP

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
bool DXSetup(HWND hWnd,HINSTANCE hInstance);

extern LPDIRECT3DDEVICE9 g_pD3DDevice;
LPDIRECT3D9 d3dObject=NULL;
LPDIRECTINPUT8 D3DInputObject=NULL;
LPDIRECTINPUTDEVICE8 D3DInputDevice=NULL;
LPDIRECTINPUTDEVICE8 D3DMouseDevice=NULL;


bool DXSetup(HWND hWnd, HINSTANCE hInstance)
{
	// Create the main Direct3D object. This object is used to initialise Direct3D
	// and to provide us with a device interface object
	    if( NULL == ( d3dObject = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        return false;

    // Set up the structure used to create the g_pD3DDevice. Since we are now
    // using more complex geometry, we will create a device with a zbuffer.
    D3DPRESENT_PARAMETERS d3dpp; 
    ZeroMemory( &d3dpp, sizeof(d3dpp) );
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

    // Create the g_pD3DDevice
    if( FAILED( d3dObject->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                      &d3dpp, &g_pD3DDevice ) ) )
    {
        return false;
    }

	HRESULT hre = DirectInput8Create(hInstance, DIRECTINPUT_VERSION,
       IID_IDirectInput8, (void**)&D3DInputObject, NULL);
	hre = D3DInputObject->CreateDevice(GUID_SysKeyboard, &D3DInputDevice, NULL);
	hre = D3DInputDevice->SetDataFormat( &c_dfDIKeyboard );
	hre = D3DInputDevice->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

	if (FAILED(DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION,
                                IID_IDirectInput8, (void**)&D3DInputObject, NULL)))
    return false;
	
	if (FAILED(D3DInputObject->CreateDevice(GUID_SysMouse, &D3DMouseDevice, NULL)))
		return false;
	if (FAILED(D3DMouseDevice->SetCooperativeLevel(hWnd, DISCL_BACKGROUND |
											DISCL_NONEXCLUSIVE)))
		return false;
	if (FAILED(D3DMouseDevice->SetDataFormat(&c_dfDIMouse)))
		return false;
	if (FAILED(D3DMouseDevice->Acquire()))
		return false;

	return true;
}


void Cleanup()
{
	if (g_pD3DDevice){
		g_pD3DDevice->Release();
		g_pD3DDevice=NULL;
	}
	if (d3dObject){
		d3dObject->Release();
		d3dObject=NULL;
	}
	if (D3DInputDevice){
		D3DInputDevice->Unacquire();
		D3DInputDevice->Release();
	}
	if (D3DInputObject){
		D3DInputObject->Release();
	}
	if (D3DMouseDevice){
		D3DMouseDevice->Release();
	}
}

#endif